package com.chaos.framework.starter.config;

import cn.hutool.core.util.IdUtil;
import com.chaos.framework.model.constant.Constants;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;

import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import java.io.IOException;

public class OpenFeignMdcFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String traceId = httpServletRequest.getHeader(Constants.TRACE_ID);
        MDC.put(Constants.TRACE_ID, StringUtils.isBlank(traceId)? IdUtil.simpleUUID() :traceId);
        chain.doFilter(request, response);
        MDC.clear();
    }
}